import { defineStore } from 'pinia';
import { setToken, clearToken } from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
import { User, SignInView, SignInCmd, UserToken } from '@/types/idm/user';
import { doUserSignIn, doUserSignOut, fetchUserCurrent } from '@/api/idm/user';
import { CommonEnum } from '@/types/global-business';
import useAppStore from '../app';

const useUserStore = defineStore('user', {
  state: (): SignInView => ({
    status: {} as CommonEnum,
    user: {} as User,
    tokenInfo: {} as UserToken,
  }),

  getters: {
    userInfo(state: SignInView): SignInView {
      return { ...state };
    },
  },

  actions: {
    switchRoles() {
      return new Promise((resolve) => {
        // this.role = this.role === 'user' ? 'admin' : 'user';
        // resolve(this.role);
        resolve(undefined);
      });
    },
    // Set user's information
    setInfo(partial: Partial<SignInView>) {
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },

    // Get user's information
    async info() {
      const currentUserRes = await fetchUserCurrent();
      this.setInfo({
        status: {
          code: 10,
          name: 'DONE',
          desc: '登录成功',
        },
        user: currentUserRes.data,
      });
    },

    // Login
    async login(loginForm: SignInCmd) {
      try {
        const signInViewRes = await doUserSignIn(loginForm);
        const signInView = signInViewRes.data;
        this.setInfo(signInView);
        if (signInView?.status?.name === 'DONE') {
          if (signInView.tokenInfo) {
            setToken(signInView?.tokenInfo?.token);

            // 加载当前用户权限
            const appStore = useAppStore();
            await appStore.fetchServerMenuConfig();
          } else {
            // TODO: soon 跳转到登录提示页面
          }
        } else {
          // TODO: soon 跳转到登录提示页面
        }
      } catch (err) {
        clearToken();
        console.error(err);
        throw err;
      }
    },
    logoutCallBack() {
      const appStore = useAppStore();
      this.resetInfo();
      clearToken();
      removeRouteListener();
      appStore.clearServerMenu();
    },
    // Logout
    async logout() {
      try {
        await doUserSignOut();
      } finally {
        this.logoutCallBack();
      }
    },
  },
});

export default useUserStore;
